package org.jeecg.modules.lock.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.modules.door.entity.LwgyJointDoor;
import org.jeecg.modules.lock.entity.LwgyDoorLock;
import org.jeecg.modules.lock.mapper.LwgyDoorLockMapper;
import org.jeecg.modules.lock.service.IOpenCloseElectricityService;
import org.jeecg.modules.lock.service.LwgyDoorLockService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA
 *
 * @Description:
 * @Author : M-JGG
 * @create 2024/4/14 13:56
 */
public class OpenCloseElectricityJob  implements Job {

    @Autowired
    private LwgyDoorLockMapper lwgyDoorLockMapper;
    @Autowired
    private LwgyDoorLockService lwgyDoorLockService;
    @Autowired
    private IOpenCloseElectricityService openCloseService;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        try {
            QueryWrapper<LwgyDoorLock> wrapper = new QueryWrapper<>();
            LocalDate date = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            wrapper.like("upload_time", date.format(formatter));
            wrapper.isNull("state").or().ne("state", 0);
            wrapper.isNull("exe_times").or().lt("exe_times", 5);
            List<LwgyDoorLock> pageList = lwgyDoorLockService.list(wrapper);
            System.out.println(" pageList------ " + pageList);

            String strOpen = "门锁常开";
            String strClose = "关闭常开";
            // 过滤出需要开电的数据
            List<LwgyDoorLock> openList = pageList.stream().filter(item -> "4".equals(item.getLogType())
                    && item.getLogAlert().contains(strOpen)).collect(Collectors.toList());

            // 过滤出需要断电的数据
            List<LwgyDoorLock> closeList = pageList.stream().filter(item -> "17".equals(item.getLogType())
                    && item.getLogAlert().contains(strClose)).collect(Collectors.toList());

            handleDoorLocks(openList, "1");
            handleDoorLocks(closeList, "2");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handleDoorLocks(List<LwgyDoorLock> doorLocks, String lx) {
        if (doorLocks != null && !doorLocks.isEmpty()) {
            try {
                List<LwgyJointDoor> doorList = lwgyDoorLockMapper.queryJointDoor();// 查询所有带门锁的房间
                doorLocks.forEach(item -> {
                    List<LwgyJointDoor> doorLists = doorList.stream().filter(doorItem -> doorItem.getThirdRoomId().equals(item.getRoomId())).collect(Collectors.toList()) ;
                    int defaultExeTimes = 0; // 设置默认值为0
                    int exeTimes = item.getExeTimes() != null ? item.getExeTimes() : defaultExeTimes;
                    AtomicInteger times = new AtomicInteger(exeTimes);
                    doorLists.forEach(doorsItem -> {
                        String xq = doorsItem.getThirdHouseName();
                        String fjh = doorsItem.getRoomNumber();
                        System.out.println("fjh ------ " + fjh);
                        String setResult = openCloseService.useSetSBKGData(xq, fjh, lx, "1");
                        if ("0".equals(setResult)) {
                            item.setState(setResult);
                        } else {
                            // 如果setResult不是0，times++
                            item.setState(setResult);
                            times.getAndIncrement();
                        }
                    });
                    // 如果没有成功，times++
                    item.setExeTimes(times.get());
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
